package cn.wolfcode.trip.app.filter;

import cn.wolfcode.trip.app.utils.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //首先获取图片的名称
        HttpServletRequest req = (HttpServletRequest) request;
        String image = req.getRequestURI();//获取除去端口和ip以外的请求名称,即"/upload/xxx.jpg"

        //判断图片是否在硬盘中
        // public File(String parent, String child)
        File file =new File(UploadUtil.IMG_BASE_PATH,image);
        if(file.exists()){
            //图片存在,先读取
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //FileUtils.writeByteArrayToFile(file,bytes);
            //再将图片写到浏览器的响应中
            response.getOutputStream().write(bytes);
        }else{
            //放行
            chain.doFilter(request,response);
        }
    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void destroy() {

    }
}
